<?php
/**
 * 报表计算业务类(Service)
 *   
 * @author wenqiang@6rooms.com
 * @version $Id: Calculate.php,v 1.0 2013/11/5 14:14:48 gaowenqiang Exp $   
 * @package sr.service.report
 *
 */
class Sr_Service_Report_Calculate extends Sr_Service_Report_Base
{
	// 秒
	const DATETIME_UNIT_DAY = 86400; //24 * 60 * 60;
	const DATETIME_UNIT_HOUR = 3600;// 60 * 60
	const DATETIME_UNIT_HALFHOUR = 1800;// 30 * 60

	/**
	 * 报表业务类
	 *
	 * @var Object(Sr_Service_Report_Base)
	 *
	 */
	protected $report;

	/**
	 * 构造器
	 *
	 * @param $params 
	 *
	 */
	public function __construct($type)
	{
		parent::__construct(array('type' => $type));
	}
	
	/**
	 * 初始化
	 *
	 */
	protected function init($options)
	{
		parent::init($options);

		// 内部参数项
		$fields = array(
			'name' => null,
			'start' => null,
			'end' => null,
			'input' => null,
		);

		$this->addFields($fields);
	}
	
	public function setup($name, $time, $input = null, $type = null)
	{
		$options = array(
			'type' => (int)$type ? $type : $this->options['type'],
			'name' => !empty($name) ? $name : $this->options['name'],
			'time' => $time ? $time : null,
			'start' => strlen($start) ? trim($start) : null,
			'input' => $input,
		);

		$params = $this->validate($options);
		if (count($params['errors'])) {// error
			return false;
		}

		$this->setOptions($params['vars']);

		$className = $this->options['name'];
		$args = array($this->options['type'], 
						$this->options['start'],
						$this->options['end'],
						$this->options['input']);
		$this->report = self::service($className, $args);
		
		return $this->report ? true : false;
	}

	/**
	 * 参数校验
	 *
	 * @param array $form 输入参数
	 * @return array
	 *
	 */
	 // ???
	protected function validate($form)
	{
		$errors = array();
		$vars = array();

		while (1) {
			// type
			if (!isset($form['type']) || !in_array((int)$form['type'], array(self::STAT_TYPE_DAY, 
								  self::STAT_TYPE_HOUR, 
								  self::STAT_TYPE_HALFHOUR)))
			{
				$errors['type'] = 'invalid args(type)';
				break;
			}
			$vars['type'] = (int)$form['type'];

			if (!isset($form['name']) || !strlen($form['name'])) {
				$errors['name'] = 'invalid args(name)';	
			}
			$vars['name'] = $form['name'];

			if (!$form['time']) {
				$errors['time'] = 'invalid args(time)';
			}
			$vars['time'] = $form['time'] + 0;

			$second = 0;
			// 添加统计列
			switch ($vars['type']) {
				case self::STAT_TYPE_DAY :
					$tmpTime = strtotime($vars['time']) - self::DATETIME_UNIT_DAY;
					$start =  date('Y-m-d 00:00:00', $tmpTime);
					$end =  date('Y-m-d 23:59:59', $tmpTime);
					break;
				case self::STAT_TYPE_HOUR :
					$tmpTime = strtotime($vars['time']) - self::DATETIME_UNIT_DAY;
					$start =  date('Y-m-d H:00:00', $tmpTime);
					$end =  date('Y-m-d H:59:59', $tmpTime);
					break;
				case self::STAT_TYPE_HALFHOUR :
					$tmpTime = strtotime($vars['time']) - self::DATETIME_UNIT_HALFHOUR;
					$mStart = date('i', $tmpTime) >= 30 ? 30 : 0;
					$mEnd = $mStart >= 30 ? 0 : 30;
					$start =  date('Y-m-d H:{$mStart}:00', $tmpTime);
					$end =  date('Y-m-d H:{$mEnd}:59', $tmpTime);
					break;
				default:
					break;
			}

			$form['start'] = $start;
			$form['end'] = $end;

			// prod
			if (!isset($form['input'])) {
				$errors['prod'] = 'intvalid prod';
				break;
			}
			
			$vars['input'] = $form['input'];
			break;
		}

		return array('errors' => $errors, 'vars' => $vars);
	}

	/**
	 * 获取数据文件名称
	 *
	 * @param string $name
	 * @return string
	 *
	 */
	protected function getDataFilename($name)
	{
		$filename = $name . '.txt';
		$path = TMP_DIR;

		return $path . $filename;
	}

	/**
	 * 生成数据文件
	 *
	 * @param mixed(array|string) $data 数据
	 * @param string $filename 文件名
	 * @return int
	 */
	public function createDataFile($data, $filename)
	{
		$content = array();

		if (is_array($data)) {
			if (empty($data)) {
				return false;
			}
			
			$values = array();

			$one = false;
			foreach ($data as $key => $val) {
				if (is_array($val)) {
					$values[] = implode('|', array_values($val));
				} else {
					$one = true;
					break;
				}
			}

			if ($one) {
				$values[] = implode('|', array_values($val));
			}

			$content = implode("\n", $values);
		} else {
			$content = $data;
		}

		return file_put_contents($filename, $conent, FILE_APPEND);
	}
	
	
	protected function getEndTime()
	{
		if ($this->options['start']) {

		}
	}

	// 开始
	public function begin($options = null)
	{
		// 校验参数并进行基础配置
		if (!$this->setup($options)) {
			return false;
		}

		// 设置参数(当前数据源名称, REPORT_TYPE, start, end)
		// 获取数据源对象并开始计算, // 接收计算结果
		$data = $this->report->stat($this->options['start'], $this->options['end'], $this->options['input']);
		if (!$data) {
			return false;
			// error
		}
		// 结果写入数据文件
		$filename = $this->getDataFilename($name);
		$success = $this->createDataFile($data, $this->options['name']);
		if ($success) {
			return $this->report->save($filename);
		}
		return false;
	}

}
